package com.lsf.dunlian.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.google.gson.Gson;
import com.lsf.dunlian.R;
import com.lsf.dunlian.adapter.GroupChatRecycleViewAdapter;
import com.lsf.dunlian.config.PreferenceUtil;
import com.lsf.dunlian.config.Urls;
import com.lsf.dunlian.constant.Constant;
import com.lsf.dunlian.databinding.ActivityAttendanceBinding;
import com.lsf.dunlian.entity.BaseEntity;
import com.lsf.dunlian.entity.CurrentAttendanceVo;
import com.lsf.dunlian.entity.UserInfoVo;
import com.lsf.dunlian.entity.UserVO;
import com.lsf.dunlian.netty.SimpleClientHandler;
import com.lsf.dunlian.utils.audio.Location;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AttendanceActivity extends Activity implements AMapLocationListener {
    private LayoutInflater inflater;
    private ActivityAttendanceBinding binding;
    public AMapLocationClient mlocationClient;
    public AMapLocationClientOption mLocationOption = null;
    private String latitude;
    private String longitude;
    private CurrentAttendanceVo vo;
    private String address;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseUtils.setStatusBar(this);
        inflater = LayoutInflater.from(this);
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_attendance, null, false);
        setContentView(binding.getRoot());
        Request();
        binding.swipeRefreshLayout.setOnRefreshListener(() -> get());
        get();
        binding.back.setOnClickListener(v->finish());
        binding.kaoqintongji.setOnClickListener(v -> startActivity(new Intent(AttendanceActivity.this,AttendanceRecordActivity.class)));
    }

    private void location() {
        mlocationClient = new AMapLocationClient(getApplicationContext());
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(AttendanceActivity.this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        mLocationOption.setInterval(60000);
        mLocationOption.setOnceLocationLatest(true);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
    }

    private void submit(String type) {
        double distance = Location.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double.parseDouble(vo.data.getLatitudeStandard()), Double.parseDouble(vo.data.getLongitudetandard()));
        OkHttpClient client = new OkHttpClient();
        String address = "startWork".equals(type) ? binding.startWordAddress.getText().toString() : binding.endWordAddress.getText().toString();
        Request request = new Request.Builder().get().url(Urls.USER_SUBMIT_ATTENDANCE + "?userId=" + PreferenceUtil.getSharedPreference(Constant.USERID) + "&type=" + type
                + "&address=" + address
                + "&latitude=" + latitude
                + "&longitude=" + longitude
                + "&distance=" + distance
        ).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    BaseEntity vo = new Gson().fromJson(result, BaseEntity.class);
                    runOnUiThread(() -> {
                        if (vo.code == 200) {
                            get();
                            Toast.makeText(AttendanceActivity.this, "打卡成功！", Toast.LENGTH_SHORT);
                        } else {
                            Toast.makeText(AttendanceActivity.this, "打卡失败！", Toast.LENGTH_SHORT);
                        }
                    });
                }
            }
        });
    }

    private void get() {
        binding.swipeRefreshLayout.setRefreshing(true);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(Urls.USER_CURRENT_ATTENDANCE_RECORD + "?userId=" + PreferenceUtil.getSharedPreference(Constant.USERID)).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    vo = new Gson().fromJson(result, CurrentAttendanceVo.class);
                    if (vo.code != 200) return;

                    runOnUiThread(() -> {
                        if (vo.data != null) {
                            if (StringUtils.isEmpty(vo.data.getStartTime())) {
                                binding.startWorkView.setBackgroundResource(R.drawable.yuan_kaoqin);

                                binding.startWorkStatus.setText("未打卡");
                                binding.startWordTime.setText(vo.data.startTimeStandard);
                                binding.startWorkView.setOnClickListener(v -> submit("startWork"));
                            } else {
                                binding.startWorkView.setBackgroundResource(R.drawable.gray_kaoqin);

                                binding.startWorkKQ.setVisibility(View.GONE);
                                binding.startWorkStatus.setText(vo.data.getStartStatus());
                                binding.startWordTime.setText(vo.data.getStartTime());
                                binding.startWordAddress.setText(vo.data.startAddress);
                            }
                            if (StringUtils.isEmpty(vo.data.getEndTime())) {
                                binding.endWorkView.setBackgroundResource(R.drawable.yuan_kaoqin);

                                binding.endWorkStatus.setText("未打卡");
                                binding.endWordTime.setText(vo.data.endTimeStandard);
                                binding.endWorkView.setOnClickListener(v -> submit("endWork"));
                            } else {
                                binding.endWorkView.setBackgroundResource(R.drawable.gray_kaoqin);

                                binding.endWorkKQ.setVisibility(View.GONE);
                                binding.endWorkStatus.setText(vo.data.getEndStatus());
                                binding.endWordTime.setText(vo.data.getEndTime());
                                binding.endWordAddress.setText(vo.data.endAddress);
                            }
                        } else {
                            Toast.makeText(AttendanceActivity.this, vo.msg, Toast.LENGTH_SHORT);
                        }
                        binding.swipeRefreshLayout.setRefreshing(false);
                    });

                }
            }
        });
    }


    public void Request() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                location();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    location();
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                address = amapLocation.getAddress();
//                amapLocation.getCountry();//国家信息
//                amapLocation.getProvince();//省信息
//                amapLocation.getCity();//城市信息
//                amapLocation.getDistrict();//城区信息
//                ;//街道信息
//                amapLocation.getStreetNum();//街道门牌号信息
//                amapLocation.getCityCode();//城市编码
//                amapLocation.getAdCode();//地区编码
//                amapLocation.getAoiName();//获取当前定位点的AOI信息
//                amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                amapLocation.getFloor();//获取当前室内定位的楼层
                String showAddrsss = amapLocation.getDistrict() + amapLocation.getStreet() + amapLocation.getStreetNum() + amapLocation.getFloor();

                latitude = String.valueOf(amapLocation.getLatitude());//获取纬度
                longitude = String.valueOf(amapLocation.getLongitude());//获取经度

                if (vo != null) {
                    float distance = CoordinateConverter.calculateLineDistance(new DPoint(Double.parseDouble(latitude), Double.parseDouble(longitude)),
                            new DPoint(Double.parseDouble(vo.data.getLatitudeStandard()), Double.parseDouble(vo.data.getLongitudetandard())));
                    if (StringUtils.isEmpty(vo.data.getStartTime())) {
                        if (distance <= 500) {
                            binding.startWorkKQ.setText("进入考勤范围：");
                            binding.startWorkKQ.setTextColor(getResources().getColor(R.color.green));
                        } else {
                            binding.startWorkKQ.setText("未进入考勤范围：");
                            binding.startWorkKQ.setTextColor(getResources().getColor(R.color.red));
                        }
                        binding.startWordAddress.setText(showAddrsss);
                    }
                    if (StringUtils.isEmpty(vo.data.getEndTime())) {
                        if (distance <= 500) {
                            binding.endWorkKQ.setText("进入考勤范围：");
                            binding.endWorkKQ.setTextColor(getResources().getColor(R.color.green));
                        } else {
                            binding.endWorkKQ.setText("未进入考勤范围：");
                            binding.endWorkKQ.setTextColor(getResources().getColor(R.color.red));
                        }
                        binding.endWordAddress.setText(showAddrsss);
                    }
                }
            } else {
                if (amapLocation.getErrorCode() == 12) {
                    Log.e("AmapError", "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo());
                    Request();
                }

//                runOnUiThread(() -> Toast.makeText(AttendanceActivity.this,amapLocation.getErrorCode() + amapLocation.getErrorInfo(),Toast.LENGTH_LONG).show());
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
        }
    }
}
